<?php
/**
 * Created by PhpStorm.
 * User: wangkk
 * Date: 2019-04-24 14:50
 * Description: {卡券核销}
 */
namespace app\controllers;
use app\models\CouponForm;
use Yii;
use app\controllers\CommonController;
use yii\data\ActiveDataProvider;
use yii\filters\VerbFilter;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use WxErrcode2Msg;
use linslin\yii2\curl;
use yii\web\Response;

class CardconsumeController extends CommonController{
    //接口地址
    public static $url = array(
        'get_code_url'      => 'https://api.weixin.qq.com/card/code/get?access_token=',     //查看code状态地址
        'consume_code_url'  => 'https://api.weixin.qq.com/card/code/consume?access_token=', //核销地址
    );

    /**
     * 核销卡券
     */
    public function actionCardconsume(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $getData = $request->get();
        if(empty($getData['orderid'])){
            return array('code'=>-1, 'msg'=>'订单号不能为空');
        }
        if(empty($getData['card_id'])){
            return array('code'=>-1, 'msg'=>'卡券批次号不能为空');
        }
        if(empty($getData['code'])){
            return array('code'=>-1, 'msg'=>'卡券code码不能为空');
        }
        $codeData = array(
            'card_id' => $getData['card_id'],
            'code'    => $getData['code'],        //正常状态的code
            'check_consume' => false   //校验code核销状态,填true和false返回结果不同，在这使用false
        );
        //获取卡券状态的接口地址
        $get_code_url = self::$url['get_code_url'];
        //核销卡券接口地址
        $consume_code_url = self::$url['consume_code_url'];
        $access_token = $this->get_access_token();
        //检测卡券code码状态
        $cardcodestatusArr = $this->checkCodeStatus($get_code_url . $access_token, $codeData);
        $cardcodestatus    = $cardcodestatusArr['code'];
        if ($cardcodestatus == 0) {
            //卡券状态正常，可以核销
            $postconsumeData = array(
                'card_id' => $getData['card_id'],
                'code' => $getData['code'],
            );
            $isconsumecard = $this->curlpostJson($consume_code_url . $access_token, $postconsumeData, true);
            if ($isconsumecard['errcode'] == 0) {
                //核销成功，写入核销记录表
                $card_consumeData = array(
                    'orderid' => $getData['orderid'],
                    'card_id' => $getData['card_id'],
                    'code'    => $getData['code'],
                    'openid'  => $isconsumecard['openid'],
                    'add_time'=> time(),
                );
                //写入核销记录
                Yii::$app->db->createCommand()->insert('wx_card_consume', $card_consumeData)->execute();
                return [
                    'code ' => 0,
                    'msg'   => '核销成功',
                ];
            } else {
                $msg = WxErrcode2Msg::errCoode2Msg($isconsumecard['errcode']);
                return [
                    'code ' => $isconsumecard['errcode'],
                    'msg' => $msg,
                ];
            }
        } else {
            //核销失败，返回状态码和提示消息
            return [
                'code ' => $cardcodestatus,
                'msg' => $cardcodestatusArr['msg'],
            ];
        }
    }

    /**
     * 核销前检查卡券状态
     * @param $url
     * @param array $data
     * @return array 卡券的状态和消息
     */
    public function checkCodeStatus($url, $data = array()){
        $result = $this->curlpostJson($url, $data, true);
        if ($result['errcode'] == 0) {
            //接口正常，再判断卡券状态
            switch ($result['user_card_status']) {
                case 'NORMAL':    //正常
                    $status = 0;
                    $msg = '卡券状态正常';
                    break;
                case 'CONSUMED':  //已核销
                    $status = 1;
                    $msg = '卡券已核销';
                    break;
                case 'EXPIRE':    //已过期
                    $status = 2;
                    $msg = '卡券已过期';
                    break;
                case 'GIFTING':   //转赠中
                    $msg = '卡券转赠中';
                    $status = 3;
                    break;
                case 'GIFT_TIMEOUT': //转赠超时
                    $status = 4;
                    $msg = '卡券转赠超时';
                    break;
                case 'DELETE':   //已删除
                    $msg = '卡券已删除';
                    $status = 5;
                    break;
                case 'UNAVAILABLE': //已失效
                    $msg = '卡券已失效';
                    $status = 6;
                    break;
                default:
                    $status = 7;  //卡券状态未知
                    $msg = '卡券未知状态';
                    break;
            }
        } else {
            //接口报错
            $status = $result['errcode'];
            $msg = '接口返回错误信息';
        }
        return array('code'=>$status, 'msg' => $msg);
    }

    /*
     * 获取卡券状态接口，对外提供
     * @param  string card_id  卡券批次号
     * @param  string code     卡券code码
     * @return json            返回状态码和提示信息
     */
    public function actionGetcodestatus(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $getData = $request->get();
        if(empty($getData['code'])){
            return array('code'=>-1, 'msg'=>'卡券code码不能为空');
        }
        $card_id = '';
        if(isset($getData['card_id'])){
            $card_id = $getData['card_id'];
        }
        $codeData = array(
            'card_id' => $card_id,
            'code'    => $getData['code'],      //正常状态的code
            'check_consume' => false            //校验code核销状态,填true和false返回结果不同，在这使用false
        );
        //获取卡券状态的接口地址
        $get_code_url = self::$url['get_code_url'];
        $access_token = $this->get_access_token();
        //检测卡券code码状态
        $cardcodestatusArr = $this->checkCodeStatus($get_code_url . $access_token, $codeData);
        return $cardcodestatusArr;
    }
}